package model

import (
	"database/sql"
	"fmt"
	g "github.com/doug-martin/goqu/v9"
	"github.com/valyala/fasthttp"
	"time"
)

type tblQuoteMangeTable struct {
	Id                  int32   `db:"id" json:"id" cbor:"id"`
	OperatorId          int     `db:"operator_id" json:"operator_id" cbor:"operator_id"`
	BalanceQuota        float64 `db:"balance_quota" json:"balance_quota" cbor:"balance_quota"`
	BalanceUsed         float64 `db:"balance_used" json:"balance_used" cbor:"balance_used"`
	CommissionQuota     float64 `db:"commission_quota" json:"commission_quota" cbor:"commission_quota"`
	CommissionUsed      float64 `db:"commission_used" json:"commission_used" cbor:"commission_used"`
	TestMemberQuota     float64 `db:"test_member_quota" json:"test_member_quota" cbor:"test_member_quota"`
	TestMemberUsed      float64 `db:"test_member_used" json:"test_member_used" cbor:"test_member_used"`
	TestMemberNum       int     `db:"test_member_num" json:"test_member_num" cbor:"test_member_num"`
	TestMemberNumUsed   int     `db:"test_member_num_used" json:"test_member_num_used" cbor:"test_member_num_used"`
	AutoWithdrawalLimit float64 `db:"auto_withdrawal_limit" json:"auto_withdrawal_limit" cbor:"auto_withdrawal_limit"`

	//UsedWithdrawalLimit float64 `db:"used_withdrawal_limit" json:"used_withdrawal_limit" cbor:"used_withdrawal_limit"`

	AutoWithdrawalSingleLimit float64 `db:"auto_withdrawal_single_limit" json:"auto_withdrawal_single_limit" cbor:"auto_withdrawal_single_limit"`
}

type tblQuoteMange struct {
	Id                  int32   `db:"id" json:"id" cbor:"id"`
	OperatorId          int     `db:"operator_id" json:"operator_id" cbor:"operator_id"`
	OperatorName        string  `db:"operator_name" json:"operator_name" cbor:"operator_name"`
	BalanceQuota        float64 `db:"balance_quota" json:"balance_quota" cbor:"balance_quota"`
	BalanceUsed         float64 `db:"balance_used" json:"balance_used" cbor:"balance_used"`
	CommissionQuota     float64 `db:"commission_quota" json:"commission_quota" cbor:"commission_quota"`
	CommissionUsed      float64 `db:"commission_used" json:"commission_used" cbor:"commission_used"`
	TestMemberQuota     float64 `db:"test_member_quota" json:"test_member_quota" cbor:"test_member_quota"`
	TestMemberUsed      float64 `db:"test_member_used" json:"test_member_used" cbor:"test_member_used"`
	TestMemberNum       int     `db:"test_member_num" json:"test_member_num" cbor:"test_member_num"`
	TestMemberNumUsed   int     `db:"test_member_num_used" json:"test_member_num_used" cbor:"test_member_num_used"`
	AutoWithdrawalLimit float64 `db:"auto_withdrawal_limit" json:"auto_withdrawal_limit" cbor:"auto_withdrawal_limit"`

	UsedWithdrawalLimit float64 `db:"used_withdrawal_limit" json:"used_withdrawal_limit" cbor:"used_withdrawal_limit"`

	AutoWithdrawalSingleLimit float64 `db:"auto_withdrawal_single_limit" json:"auto_withdrawal_single_limit" cbor:"auto_withdrawal_single_limit"`
}

// 游戏记录数据
type OperatorQuoteData struct {
	T int64           `json:"total" cbor:"t"`
	D []tblQuoteMange `json:"d" cbor:"d"`
	S uint            `json:"s"`
}

type OperatorQuoteParam struct {
	OperatorId string `json:"operator_id" cbor:"operator_id"`
	Page       int    `json:"page" cbor:"page"`
	PageSize   int    `json:"page_size" cbor:"page_size"`
}

// 运营商额度列表
func GetOpeartorQuoteList(param OperatorQuoteParam, ctx *fasthttp.RequestCtx) (OperatorQuoteData, error) {
	data := OperatorQuoteData{}

	t := dialect.From(g.T("tbl_operator_quota_manage").As("a"))

	ex := g.Ex{}
	loginUser := GetLoginUser(ctx)
	if loginUser.Operator != "" {
		ex["tbl_operator_info.id"] = loginUser.Operator
	}
	if param.OperatorId != "" {
		ex["tbl_operator_info.id"] = param.OperatorId
	}
	if param.Page >= 1 {
		query, _, _ := t.Select(g.COUNT("a.id")).LeftJoin(g.T("tbl_operator_info"),
			g.On(g.Ex{"a.operator_id": g.I("tbl_operator_info.id")})).Where(ex).ToSQL()
		err := meta.MerchantDB.Get(&data.T, query)
		if err != nil && err != sql.ErrNoRows {
			return data, pushLog(fmt.Errorf("%s,[%s]", err.Error(), query), "数据库错误")
		}
		if data.T == 0 {
			return data, nil
		}
	}

	offset := (param.Page - 1) * param.PageSize
	var d []tblQuoteMange
	query, _, _ := dialect.Select("a.*", "tbl_operator_info.operator_name").From(g.T("tbl_operator_quota_manage").As("a")).LeftJoin(g.T("tbl_operator_info"),
		g.On(g.Ex{"a.operator_id": g.I("tbl_operator_info.id")})).Where(ex).Order(g.I("operator_id").Desc()).Offset(uint(offset)).Limit(uint(param.PageSize)).ToSQL()

	err := meta.MerchantDB.Select(&d, query)
	if err != nil {
		return data, pushLog(fmt.Errorf("%s,[%s]", err.Error(), query), "数据库错误")
	}
	if len(d) == 0 {
		return data, nil
	}
	data.D = d
	monthDate := time.Now().Format("2006-01")
	monthDate = monthDate + "-01"
	for key, value := range data.D {
		var withdrawLimit = 0.00
		SqlSelect := fmt.Sprintf("select IFNULL(sum(withdraw),0) from tbl_report_daily where business_id = 0 and operator_id=%d and created_at>='%s'", value.OperatorId, monthDate)
		meta.MerchantDB.Get(&withdrawLimit, SqlSelect)
		(data.D)[key].UsedWithdrawalLimit = withdrawLimit
	}
	data.S = uint(param.PageSize)
	return data, nil
}

type AddOperatorQuoteParam struct {
	OperatorId                string  `json:"operator_id" db:"operator_id" cbor:"operator_id"`
	BalanceQuota              float64 `json:"balance_quota" db:"balance_quota" cbor:"balance_quota"`
	CommissionQuota           float64 `json:"commission_quota" db:"commission_quota" cbor:"commission_quota"`
	TestMemberQuota           float64 `json:"test_member_quota" db:"test_member_quota" cbor:"test_member_quota"`
	TestMemberNum             float64 `json:"test_member_num" db:"test_member_num" cbor:"test_member_num"`
	AutoWithdrawalLimit       float64 `json:"auto_withdrawal_limit" db:"auto_withdrawal_limit" cbor:"auto_withdrawal_limit"`
	AutoWithdrawalSingleLimit float64 `db:"auto_withdrawal_single_limit" json:"auto_withdrawal_single_limit" cbor:"auto_withdrawal_single_limit"`
}

// /添加额度
func AddOperatorQuote(param AddOperatorQuoteParam) error {

	var total int
	t := dialect.From("tbl_operator_quota_manage")
	query, _, _ := t.Select(g.COUNT("id")).Where(g.Ex{"operator_id": param.OperatorId}).ToSQL()
	err := meta.MerchantDB.Get(&total, query)
	if err != nil {
		return pushLog(fmt.Errorf("%s,[%s]", err.Error(), query), "数据库错误")
	}
	if total > 0 {
		query, _, _ := dialect.Update("tbl_operator_quota_manage").Set(&param).Where(g.Ex{"operator_id": param.OperatorId}).ToSQL()
		_, err = meta.MerchantDB.Exec(query)
		if err != nil {
			return pushLog(fmt.Errorf("%s,[%s]", err.Error(), query), "数据库错误")
		}

	} else {
		query, _, _ := dialect.Insert("tbl_operator_quota_manage").Rows(param).ToSQL()
		_, err = meta.MerchantDB.Exec(query)
		if err != nil {
			return pushLog(fmt.Errorf("%s,[%s]", err.Error(), query), "数据库错误")
		}
	}
	return nil
}

func GetQuoteDataByOperatorId(operator_id string) (tblQuoteMangeTable, error) {
	data := tblQuoteMangeTable{}
	query, _, _ := dialect.From("tbl_operator_quota_manage").Select("*").Where(g.Ex{"operator_id": operator_id}).ToSQL()
	err := meta.MerchantDB.Get(&data, query)
	if err != nil {
		return data, err
	}
	return data, nil
}
func UpdateQuote(record tblQuoteMangeTable) error {
	query, _, _ := dialect.From("tbl_operator_quota_manage").Where(g.Ex{"operator_id": record.OperatorId}).Update().Set(record).ToSQL()
	_, err := meta.MerchantDB.Exec(query)
	if err != nil {
		return err
	}
	return nil
}
